<?php
/*
 * 获取路由名称转化为CSS Class名称
 * */
function model_admin_link($title, $model)
{
    return model_link($title, $model, 'admin');
}

function model_link($title, $model, $prefix = '')
{
    // 获取数据模型的复数蛇形命名
    $model_name = model_plural_name($model);

    // 初始化前缀
    $prefix = $prefix ? "/$prefix/" : '/';

    // 使用站点 URL 拼接全量 URL
    $url = config('app.url') . $prefix . $model_name . '/' . $model->id;

    // 拼接 HTML A 标签，并返回
    return '<a href="' . $url . '" target="_blank">' . $title . '</a>';
}

function model_plural_name($model)
{
    // 从实体中获取完整类名，例如：App\Models\User
    $full_class_name = get_class($model);

    // 获取基础类名，例如：传参 `App\Models\User` 会得到 `User`
    $class_name = class_basename($full_class_name);
    //dd($class_name);
    // 蛇形命名，例如：传参 `User`  会得到 `user`, `FooBar` 会得到 `foo_bar`
    $snake_case_name = snake_case($class_name);
    //dd($class_name);
    // 获取子串的复数形式，例如：传参 `user` 会得到 `users`
    return str_plural($snake_case_name);
}

function route_class()
{
    return str_replace('.', '-', Route::currentRouteName());
}

//生成文章摘要
function make_excerpt($value, $length = 200)
{
    $excerpt = trim(preg_replace('/\r\n|\r|\n+/', ' ', strip_tags($value)));
    return str_limit($excerpt, $length);
}

//裁剪内容长度
function getTitleFormMbSubstr($title,$begin=0,$defaultLength=40,$defaultFormat='UTF-8')
{
    if (mb_strlen($title)>=$defaultLength){
        $result=mb_substr($title,$begin,$defaultLength,$defaultFormat)." ...";
        return $result;
    }else{
        return $title;
    }
}

/**
 * 验证是否是中国验证码.
 *
 * @param string $number
 * @return bool
 */
function validateChinaPhoneNumber(string $number): bool
{
    return preg_match('/^(\+?0?86\-?)?((13\d|14[57]|15[^4,\D]|17[3678]|18\d)\d{8}|170[059]\d{7})$/', $number);
}
/**
 * 验证用户名是否合法.
 *
 * @param string $username
 * @return bool
 */
function validateUsername(string $username): bool
{
    return preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $username);
}
/**
 * Get user login field.
 *
 * @param string $login
 * @param string $default
 * @return string
 * @author Seven Du <shiweidu@outlook.com>
 */
function username(string $login, string $default = 'id'): string
{
    $map = [
        //'email' => filter_var($login, FILTER_VALIDATE_EMAIL),
        'mobile' => validateChinaPhoneNumber($login),
        'name' => validateUsername($login),
    ];
    foreach ($map as $field => $value) {
        if ($value) {
            return $field;
        }
    }
    return $default;
}

/*
 * 短信发送
 */
function seed_sms_code($phone,$msg=null,$code=null)
{
    if($code==null)
    {
        $randStr = str_shuffle('1234567890');
        $code = substr($randStr,0,6);
        session(['SmsTmpCode' => $code]);
        session(['SmsTmpMobile' => $phone]);
        session(['SmsTmpCodeBeginTime' => time()]);
    }
  //  exit(session('SmsTmpCode'));
    if($msg==null){ $msg="【爱达人】".$code."（动态验证码),请在20分钟内填写"; }
    $url="http://service.winic.org:8009/sys_port/gateway/index.asp?";
    $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
    $id = iconv("UTF-8","GB2312",'爱达人');;
    $pwd = 'dishuidaren';
    $to = $phone;
    $content = iconv("UTF-8","GB2312",$msg);
    $rdata = sprintf($data, $id, $pwd, $to, $content);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$rdata);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

    if(env('APP_ENV')=="local")
    {
        curl_close($ch);
        return session('SmsTmpCode');
    }else
    {
        $result = curl_exec($ch);
        curl_close($ch);
        $result = substr($result,0,3);
        return $result;
    }
}


function get_db_config()
{
    if (getenv('IS_IN_HEROKU')) {
        $url = parse_url(getenv("DATABASE_URL"));
        $redis = new Predis\Client(getenv('REDIS_URL'));
        return $db_config = [
            'connection' => 'pgsql',
            'host' => $url["host"],
            'database'  => substr($url["path"], 1),
            'username'  => $url["user"],
            'password'  => $url["pass"],
        ];
    } else {
        return $db_config = [
            'connection' => env('DB_CONNECTION', 'mysql'),
            'host' => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
        ];
    }
}